package com.example.library_log;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

public class ComTools {
    private static final String TAG = "ComTools";

//    /**
//     * 使用Gson将Json字符串转换为对象
//     * 将字符串转换为 对象
//     *
//     * @param json
//     * @param type
//     * @return
//     */
//    public static <T> T JsonToObject(String json, Class<T> type) {
//        try {
//            Gson gson = new Gson();
//            return gson.fromJson(json, type);
//        } catch (Throwable e) {
//            e.printStackTrace();
//            ChenLog.i("JsonToObject: json:", json, " error:", e.getMessage());
//            return null;
//        }
//
//    }

    public static String parseArray(int[] array) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            sb.append("[" + i + "]").append(array[i]).append(" ");
        }
        return sb.toString();
    }

    public static String mapToString(String name, Map<?, ?> map) {
        StringBuilder result = new StringBuilder(name).append(">>>>>>>>:\n");

        for (Map.Entry<?, ?> entry : map.entrySet()) {
            result.append(entry.getKey()).append(":").append(entry.getValue()).append("  ");
        }
        result.append("\n----------->end");
        return result.toString();
    }


    public static String listMapToString(String name, List<Map<String, String>> lisMap) {
        StringBuilder result = new StringBuilder(name).append(">：");

        for (Map<String, String> map : lisMap) {
            String s = mapToString("", map);
            result.append(s);
        }


        return result.toString();
    }

    private static final Map<String, Object> values = new HashMap<>();

    public static <T> void put(String key, T value, Class<T> valueType) {
        values.put(key, value);
    }

    public static <T> T get(String key, Class<T> valueType) {
        return (T) values.get(key);
    }

    /**
     * 将字符串转成MD5值
     *
     * @param string 需要转换的字符串
     * @return 字符串的MD5值
     */
    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }


    public static String readSp(Context context, String fileName, String key, String def) {
        if (context == null) {
            return TextUtils.isEmpty(def) ? "" : def;
        }
        SharedPreferences sp = context.getSharedPreferences(fileName, MODE_PRIVATE);
        String readContent = sp.getString(key, def);
        return readContent;
    }

    public static boolean saveToPre(Context context, String fileName, String key, String val) {
        if (context == null || TextUtils.isEmpty(fileName)) {
            ChenLog.i("saveToPre  null context or empty filename");
            return false;
        }
        SharedPreferences sp = context.getSharedPreferences(fileName, MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, val);
        edit.apply();
        ChenLog.i("saveToPre:", " >", fileName, " > key:", key, " val:", val);
        return true;
    }


    public static boolean saveStr2File(String content, String filePath) {
        ChenLog.i(TAG, " path:", filePath, " content:", content);
        FileWriter fileWriter = null;
        boolean result = false;
        try {
            fileWriter = new FileWriter(filePath);
            fileWriter.write(content);
            result = true;
        } catch (Throwable e) {
            e.printStackTrace();
            result = false;

        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.flush();
                    fileWriter.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

    }


    public static String readFromFile(String filePath) {
        StringBuilder sb = new StringBuilder();

        File file = new File(filePath);
        if (!file.exists()) {
            ChenLog.i(TAG, " file not exit:", filePath);
            return "";
        }

        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;

        try {

            inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }

            return sb.toString();
        }
    }
}
